import { interpreter } from "@/api/request";
import { GetUserInfoApi, UpdateUserInfoApi } from "@/api/user";
import { defineStore } from "pinia";
import { computed, ref } from "vue";

interface UpdateProps {
  user_name: string;
  area?: string;
  /**
   * 日期格式 yyyy-mm-dd
   */
  birthday?: string;
  city?: string;
  profile_photo?: string;
  /**
   * 1 男 2  女
   */
  gender?: number;
  info?: string;
  province?: string;
  vip_user?: null | {
    user_level: string;
    vip_expire_at: string;
  };
  [property: string]: any;
}

export const useUserInfo = defineStore("userInfo", () => {
  const userInfo = ref<UpdateProps>({
    vip_user: null,
    user_name: "",
    province: "",
    city: "",
    area: "",
    birthday: ""
  });

  const handleUpdateInfo = (info: UpdateProps) => {
    userInfo.value = info;
  };
  const getUserInfo = async () => {
    const [err, res] = await interpreter(GetUserInfoApi());
    if (!err) {
      console.log(res);
      userInfo.value = res;
    }
  };

  const updateUserInfo = async (props: UpdateProps) => {
    const [err] = await interpreter(UpdateUserInfoApi(props));
    if (!err) {
      userInfo.value = props;
    }
  };
  const resetUserInfo = () => {
    userInfo.value = {
      vip_user: null,
      user_name: "",
      province: "",
      city: "",
      area: "",
      birthday: ""
    };
  };

  const formatVip = computed(() => {
    const format: Record<string, string> = {
      day_vip_user: "天卡",
      week_vip_user: "周卡",
      month_vip_user: "月卡",
      year_vip_user: "年卡"
    };
    if (userInfo.value.vipUser) {
      return format[userInfo.value.vipUser.user_level];
    }
    return "";
  });

  const isVip = computed(() => {
    const { vipuser } = userInfo.value;
    if (!vipuser || vipuser.user_level === "normal_user") {
      return false;
    }
    return true;
  });

  return {
    userInfo,
    formatVip,
    isVip,
    resetUserInfo,
    handleUpdateInfo,
    getUserInfo,
    updateUserInfo
  };
});
